import React, {useState, useEffect} from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  TextInput,
  Alert,
  FlatList,
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import AsyncStorage from '@react-native-async-storage/async-storage';
import DatePicker from 'react-native-date-picker';
import Modal from 'react-native-modal';
import {Picker} from '@react-native-picker/picker';

const ExerciseTracker = () => {
  const [exerciseData, setExerciseData] = useState([]);
  const [showForm, setShowForm] = useState(false);
  const [editingId, setEditingId] = useState(null);
  const [showDatePicker, setShowDatePicker] = useState(false);
  const [formData, setFormData] = useState({
    date: new Date(),
    type: '',
    duration: '',
    calories: '',
    note: '',
  });

  const exerciseTypes = [
    '跑步',
    '快走',
    '游泳',
    '骑行',
    '瑜伽',
    '力量训练',
    '跳绳',
    '爬山',
    '篮球',
    '足球',
    '羽毛球',
    '乒乓球',
    '健身操',
    '普拉提',
    '舞蹈',
    '其他',
  ];

  // 从AsyncStorage加载数据
  useEffect(() => {
    const loadData = async () => {
      try {
        const data = await AsyncStorage.getItem('exerciseData');
        if (data) {
          setExerciseData(JSON.parse(data));
        }
      } catch (error) {
        console.error('加载运动数据失败:', error);
      }
    };

    loadData();
  }, []);

  // 保存数据到AsyncStorage
  const saveData = async newData => {
    try {
      await AsyncStorage.setItem('exerciseData', JSON.stringify(newData));
    } catch (error) {
      console.error('保存运动数据失败:', error);
    }
  };

  // 提交表单
  const handleSubmit = () => {
    if (!formData.type || !formData.duration || !formData.calories) {
      Alert.alert('错误', '请填写完整的运动信息');
      return;
    }

    const newEntry = {
      id: editingId || Date.now(),
      date: formData.date.toISOString().split('T')[0],
      type: formData.type,
      duration: parseInt(formData.duration),
      calories: parseInt(formData.calories),
      note: formData.note,
    };

    let newData;
    if (editingId) {
      newData = exerciseData.map(item =>
        item.id === editingId ? newEntry : item,
      );
      setEditingId(null);
    } else {
      newData = [...exerciseData, newEntry].sort(
        (a, b) => new Date(b.date) - new Date(a.date),
      );
    }

    setExerciseData(newData);
    saveData(newData);

    setFormData({
      date: new Date(),
      type: '',
      duration: '',
      calories: '',
      note: '',
    });
    setShowForm(false);
  };

  // 编辑记录
  const handleEdit = item => {
    setFormData({
      date: new Date(item.date),
      type: item.type,
      duration: item.duration.toString(),
      calories: item.calories.toString(),
      note: item.note,
    });
    setEditingId(item.id);
    setShowForm(true);
  };

  // 删除记录
  const handleDelete = id => {
    Alert.alert('确认删除', '确定要删除这条记录吗？', [
      {text: '取消', style: 'cancel'},
      {
        text: '删除',
        style: 'destructive',
        onPress: () => {
          const newData = exerciseData.filter(item => item.id !== id);
          setExerciseData(newData);
          saveData(newData);
        },
      },
    ]);
  };

  // 取消编辑
  const handleCancel = () => {
    setFormData({
      date: new Date(),
      type: '',
      duration: '',
      calories: '',
      note: '',
    });
    setEditingId(null);
    setShowForm(false);
  };

  // 格式化日期
  const formatDate = dateString => {
    const date = new Date(dateString);
    return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
  };

  // 获取运动类型图标
  const getExerciseIcon = type => {
    const iconMap = {
      跑步: 'directions-run',
      快走: 'directions-walk',
      游泳: 'pool',
      骑行: 'directions-bike',
      瑜伽: 'self-improvement',
      力量训练: 'fitness-center',
      跳绳: 'sports',
      爬山: 'terrain',
      篮球: 'sports-basketball',
      足球: 'sports-soccer',
      羽毛球: 'sports-tennis',
      乒乓球: 'sports-tennis',
      健身操: 'sports-gymnastics',
      普拉提: 'self-improvement',
      舞蹈: 'music-note',
      其他: 'sports',
    };
    return iconMap[type] || 'sports';
  };

  // 按日期分组数据
  const groupedData = exerciseData.reduce((groups, item) => {
    const date = item.date;
    if (!groups[date]) {
      groups[date] = [];
    }
    groups[date].push(item);
    return groups;
  }, {});

  // 计算每日总运动时长和卡路里
  const getDailyStats = date => {
    const dayData = groupedData[date] || [];
    const totalDuration = dayData.reduce((sum, item) => sum + item.duration, 0);
    const totalCalories = dayData.reduce((sum, item) => sum + item.calories, 0);
    return {totalDuration, totalCalories};
  };

  // 渲染运动记录项
  const renderExerciseItem = ({item}) => {
    return (
      <View style={styles.entryCard}>
        <View style={styles.entryHeader}>
          <View style={styles.exerciseInfo}>
            <Icon
              name={getExerciseIcon(item.type)}
              size={20}
              color="#667eea"
            />
            <Text style={styles.exerciseType}>{item.type}</Text>
          </View>
          <View style={styles.entryActions}>
            <TouchableOpacity
              style={styles.editBtn}
              onPress={() => handleEdit(item)}>
              <Icon name="edit" size={20} color="#667eea" />
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.deleteBtn}
              onPress={() => handleDelete(item.id)}>
              <Icon name="delete" size={20} color="#e74c3c" />
            </TouchableOpacity>
          </View>
        </View>

        <View style={styles.entryContent}>
          <View style={styles.statsRow}>
            <View style={styles.statItem}>
              <Icon name="schedule" size={16} color="#666" />
              <Text style={styles.statText}>{item.duration} 分钟</Text>
            </View>
            <View style={styles.statItem}>
              <Icon name="local-fire-department" size={16} color="#666" />
              <Text style={styles.statText}>{item.calories} 卡路里</Text>
            </View>
          </View>
          {item.note && <Text style={styles.entryNote}>{item.note}</Text>}
        </View>
      </View>
    );
  };

  // 渲染日期分组
  const renderDateGroup = date => {
    const dayData = groupedData[date];
    const {totalDuration, totalCalories} = getDailyStats(date);

    return (
      <View key={date} style={styles.dateGroup}>
        <View style={styles.dateHeader}>
          <Text style={styles.dateTitle}>{formatDate(date)}</Text>
          <View style={styles.dailyStats}>
            <Text style={styles.dailyStatText}>
              {totalDuration}分钟 · {totalCalories}卡路里
            </Text>
          </View>
        </View>
        {dayData.map(item => (
          <View key={item.id}>{renderExerciseItem({item})}</View>
        ))}
      </View>
    );
  };

  return (
    <View style={styles.container}>
      {/* 添加按钮 */}
      <TouchableOpacity style={styles.addBtn} onPress={() => setShowForm(true)}>
        <Icon name="add" size={24} color="#fff" />
        <Text style={styles.addBtnText}>添加运动记录</Text>
      </TouchableOpacity>

      {/* 运动记录列表 */}
      <ScrollView
        showsVerticalScrollIndicator={false}
        contentContainerStyle={styles.listContainer}>
        {Object.keys(groupedData).length > 0 ? (
          Object.keys(groupedData)
            .sort((a, b) => new Date(b) - new Date(a))
            .map(date => renderDateGroup(date))
        ) : (
          <View style={styles.emptyContainer}>
            <Icon name="fitness-center" size={60} color="#ccc" />
            <Text style={styles.emptyText}>还没有运动记录</Text>
            <Text style={styles.emptySubText}>点击上方按钮添加第一条记录</Text>
          </View>
        )}
      </ScrollView>

      {/* 添加/编辑表单模态框 */}
      <Modal
        isVisible={showForm}
        onBackdropPress={handleCancel}
        style={styles.modal}>
        <View style={styles.formContainer}>
          <Text style={styles.formTitle}>
            {editingId ? '编辑运动记录' : '添加运动记录'}
          </Text>

          {/* 日期选择 */}
          <TouchableOpacity
            style={styles.dateButton}
            onPress={() => setShowDatePicker(true)}>
            <Icon name="calendar-today" size={20} color="#667eea" />
            <Text style={styles.dateButtonText}>
              {formData.date.toLocaleDateString('zh-CN')}
            </Text>
          </TouchableOpacity>

          {/* 运动类型选择 */}
          <View style={styles.inputGroup}>
            <Text style={styles.inputLabel}>运动类型</Text>
            <View style={styles.pickerContainer}>
              <Picker
                selectedValue={formData.type}
                onValueChange={value => setFormData({...formData, type: value})}>
                <Picker.Item label="请选择运动类型" value="" />
                {exerciseTypes.map(type => (
                  <Picker.Item key={type} label={type} value={type} />
                ))}
              </Picker>
            </View>
          </View>

          {/* 运动时长输入 */}
          <View style={styles.inputGroup}>
            <Text style={styles.inputLabel}>运动时长 (分钟)</Text>
            <TextInput
              style={styles.input}
              value={formData.duration}
              onChangeText={text => setFormData({...formData, duration: text})}
              placeholder="请输入运动时长"
              keyboardType="numeric"
            />
          </View>

          {/* 卡路里输入 */}
          <View style={styles.inputGroup}>
            <Text style={styles.inputLabel}>消耗卡路里</Text>
            <TextInput
              style={styles.input}
              value={formData.calories}
              onChangeText={text => setFormData({...formData, calories: text})}
              placeholder="请输入消耗的卡路里"
              keyboardType="numeric"
            />
          </View>

          {/* 备注输入 */}
          <View style={styles.inputGroup}>
            <Text style={styles.inputLabel}>备注</Text>
            <TextInput
              style={[styles.input, styles.noteInput]}
              value={formData.note}
              onChangeText={text => setFormData({...formData, note: text})}
              placeholder="添加备注（可选）"
              multiline
              numberOfLines={3}
            />
          </View>

          {/* 按钮组 */}
          <View style={styles.buttonGroup}>
            <TouchableOpacity style={styles.cancelBtn} onPress={handleCancel}>
              <Text style={styles.cancelBtnText}>取消</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.submitBtn} onPress={handleSubmit}>
              <Text style={styles.submitBtnText}>
                {editingId ? '更新' : '添加'}
              </Text>
            </TouchableOpacity>
          </View>
        </View>
      </Modal>

      {/* 日期选择器 */}
      <DatePicker
        modal
        open={showDatePicker}
        date={formData.date}
        mode="date"
        onConfirm={date => {
          setShowDatePicker(false);
          setFormData({...formData, date});
        }}
        onCancel={() => {
          setShowDatePicker(false);
        }}
        title="选择日期"
        confirmText="确认"
        cancelText="取消"
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
    padding: 15,
  },
  addBtn: {
    backgroundColor: '#667eea',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    padding: 15,
    borderRadius: 12,
    marginBottom: 15,
  },
  addBtnText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
    marginLeft: 8,
  },
  listContainer: {
    paddingBottom: 20,
  },
  dateGroup: {
    marginBottom: 20,
  },
  dateHeader: {
    backgroundColor: '#fff',
    padding: 15,
    borderRadius: 12,
    marginBottom: 10,
    shadowColor: '#000',
    shadowOffset: {width: 0, height: 2},
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 2,
  },
  dateTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 5,
  },
  dailyStats: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  dailyStatText: {
    fontSize: 14,
    color: '#667eea',
    fontWeight: 'bold',
  },
  entryCard: {
    backgroundColor: '#fff',
    borderRadius: 12,
    padding: 15,
    marginBottom: 10,
    marginLeft: 10,
    shadowColor: '#000',
    shadowOffset: {width: 0, height: 2},
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 2,
  },
  entryHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 10,
  },
  exerciseInfo: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  exerciseType: {
    fontSize: 16,
    fontWeight: 'bold',
    marginLeft: 8,
    color: '#333',
  },
  entryActions: {
    flexDirection: 'row',
    gap: 10,
  },
  editBtn: {
    padding: 5,
  },
  deleteBtn: {
    padding: 5,
  },
  entryContent: {
    flex: 1,
  },
  statsRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 5,
  },
  statItem: {
    flexDirection: 'row',
    alignItems: 'center',
    flex: 1,
  },
  statText: {
    fontSize: 14,
    color: '#666',
    marginLeft: 5,
  },
  entryNote: {
    fontSize: 14,
    color: '#666',
    fontStyle: 'italic',
    marginTop: 5,
  },
  emptyContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 60,
  },
  emptyText: {
    fontSize: 18,
    color: '#999',
    marginTop: 15,
  },
  emptySubText: {
    fontSize: 14,
    color: '#ccc',
    marginTop: 5,
  },
  modal: {
    justifyContent: 'flex-end',
    margin: 0,
  },
  formContainer: {
    backgroundColor: '#fff',
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
    padding: 20,
    maxHeight: '80%',
  },
  formTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
    marginBottom: 20,
    color: '#333',
  },
  dateButton: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#f8f9fa',
    padding: 15,
    borderRadius: 8,
    marginBottom: 15,
  },
  dateButtonText: {
    marginLeft: 10,
    fontSize: 16,
    color: '#333',
  },
  inputGroup: {
    marginBottom: 15,
  },
  inputLabel: {
    fontSize: 14,
    fontWeight: 'bold',
    marginBottom: 5,
    color: '#333',
  },
  input: {
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 8,
    padding: 12,
    fontSize: 16,
    backgroundColor: '#fff',
  },
  pickerContainer: {
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 8,
    backgroundColor: '#fff',
  },
  noteInput: {
    height: 80,
    textAlignVertical: 'top',
  },
  buttonGroup: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: 20,
  },
  cancelBtn: {
    flex: 1,
    backgroundColor: '#f8f9fa',
    padding: 15,
    borderRadius: 8,
    marginRight: 10,
  },
  cancelBtnText: {
    textAlign: 'center',
    fontSize: 16,
    color: '#666',
  },
  submitBtn: {
    flex: 1,
    backgroundColor: '#667eea',
    padding: 15,
    borderRadius: 8,
    marginLeft: 10,
  },
  submitBtnText: {
    textAlign: 'center',
    fontSize: 16,
    color: '#fff',
    fontWeight: 'bold',
  },
});

export default ExerciseTracker;
